﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GestionePolveri2.DAL;
using ControlsLib;
using GestionePolveri2.Reports;
using ExceptionReporting;
using GestionePolveriLib.BL;
using System.Threading;
using ControlsLib.SplashScreen;
using GestionePolveriLib.Facades;

namespace GestionePolveri2
{
    public partial class GestionePolveri : Form
    {
        Dictionary<string, Form> m_formCash = new Dictionary<string, Form>();
        System.Security.Principal.IPrincipal m_operatore = null;
        Form m_currentForm = null;

        KeystrokMessageFilter keyStrokeMessageFilter = new KeystrokMessageFilter();

        public GestionePolveri()
        {
            InitializeComponent();

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            //Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            ExceptionReporter reporter = new ExceptionReporter();
            reporter.Show(e.Exception);
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            ExceptionReporter reporter = new ExceptionReporter();
            reporter.Show((Exception)e.ExceptionObject);
        }

        protected override void OnLoad(EventArgs e)
        {
            // qui apre la finesta di login...
            base.OnLoad(e);

            //InitializeToolbar();

            DoLogin();

            keyStrokeMessageFilter.KeyCombinationPressed += new EventHandler(keyStrokeMessageFilter_KeyCombinationPressed);
            Application.AddMessageFilter(keyStrokeMessageFilter);
        }

        void keyStrokeMessageFilter_KeyCombinationPressed(object sender, EventArgs e)
        {
            OperatorePrincipal m_OperatorePrincipale = (OperatorePrincipal)System.Threading.Thread.CurrentPrincipal;
            if (m_OperatorePrincipale.IsInRole("Amministrazione") || m_OperatorePrincipale.IsInRole("Acquisti"))
            {
                ShowForm<Amministrazione2>();
            }
        }

        private void InitializeToolbar()
        {
            //this.mainToolbar1.Visible = false;
           
            //this.mainToolbar1.AddComboImpiantiFittizi();
            //this.mainToolbar1.AddComboImpianti();
            //this.mainToolbar1.AddComboTurni();
        }

        private void DoLogin()
        {
            LoginForm lf = new LoginForm();
            lf.ApplicationShutdown += new EventHandler(lf_ApplicationShutdown);
            if (lf.ShowDialog((IWin32Window)this) == System.Windows.Forms.DialogResult.OK)
            {
                this.Text = string.Format("Gestione Polveri [Operatore: {0}]", lf.Operatore.UserName);

                //configurazioneToolStripMenuItem.Visible = false;

                m_operatore = System.Threading.Thread.CurrentPrincipal;
                if (m_operatore.IsInRole("Acquisti"))
                {
                    caricoToolStripMenuItem.Visible = false;
                    scaricoToolStripMenuItem.Visible = false;
                    refresfCacheToolStripMenuItem.Visible = false;
                    reportDirezionaleToolStripMenuItem2.Visible = false;
                    quickReportToolStripMenuItem.Visible = false;
                    lottiToolStripMenuItem.Visible = false;
                    controlloAccessoVerniciatoriToolStripMenuItem.Visible = false;
                    elencoPartiteToolStripMenuItem.Visible = false;

                    //
                    anagraficheToolStripMenuItem.Visible = true;
                    toolStripSeparator1.Visible = false;

                    operatoriToolStripMenuItem.Visible = false;
                    ruoliToolStripMenuItem.Visible = false;
                    impiantiToolStripMenuItem.Visible = false;
                    scatoleToolStripMenuItem.Visible = false;
                    fornitoriToolStripMenuItem.Visible = false;
                    famiglieColoriToolStripMenuItem.Visible = false;
                    coloriToolStripMenuItem.Visible = false;
                    polveriToolStripMenuItem1.Visible = true;
                    configurazioneMaschereToolStripMenuItem.Visible = false;
                    turniToolStripMenuItem.Visible = false;
                    lottiToolStripMenuItem.Visible = false;
                    gestioneFormuleOrfaneToolStripMenuItem.Visible = false;
                    elencoFattureToolStripMenuItem.Visible = false;
                    elencoPOSToolStripMenuItem.Visible = false;
                    gestioneTipologiaScortaMinimaToolStripMenuItem.Visible = false;
                }
                if (m_operatore.IsInRole("Direzione"))
                {
                    caricoToolStripMenuItem.Visible = false;
                    scaricoToolStripMenuItem.Visible = true;
                    amministrazione2ToolStripMenuItem.Visible = false;
                    refresfCacheToolStripMenuItem.Visible = false;
                    anagraficheToolStripMenuItem.Visible = false;
                    lottiToolStripMenuItem.Visible = false;
                    controlloAccessoVerniciatoriToolStripMenuItem.Visible = false;
                }
                if (m_operatore.IsInRole("Produzione"))
                {
                    caricoToolStripMenuItem.Visible = false;
                    scaricoToolStripMenuItem.Visible = true;
                    amministrazione2ToolStripMenuItem.Visible = false;
                    refresfCacheToolStripMenuItem.Visible = false;
                    anagraficheToolStripMenuItem.Visible = false;
                    reportDirezionaleToolStripMenuItem2.Visible = false;
                    quickReportToolStripMenuItem.Visible = false;
                    visualizzaRagguppamentoToolStripMenuItem.Visible = true;
                    lottiToolStripMenuItem.Visible = false;
                    controlloAccessoVerniciatoriToolStripMenuItem.Visible = false;
                }

                if (m_operatore.IsInRole("Verniciatura"))
                {
                    amministrazione2ToolStripMenuItem.Visible = false;
                    refresfCacheToolStripMenuItem.Visible = false;
                    reportDirezionaleToolStripMenuItem2.Visible = false;
                    quickReportToolStripMenuItem.Visible = false;
                    lottiToolStripMenuItem.Visible = false;
                    controlloAccessoVerniciatoriToolStripMenuItem.Visible = false;

                    anagraficheToolStripMenuItem.Visible = true;

                    operatoriToolStripMenuItem.Visible = false;
                    ruoliToolStripMenuItem.Visible = false;
                    impiantiToolStripMenuItem.Visible = false;
                    scatoleToolStripMenuItem.Visible = false;
                    fornitoriToolStripMenuItem.Visible = false;
                    famiglieColoriToolStripMenuItem.Visible = false;
                    coloriToolStripMenuItem.Visible = false;
                    polveriToolStripMenuItem1.Visible = false;
                    configurazioneMaschereToolStripMenuItem.Visible = false;
                    turniToolStripMenuItem.Visible = false;
                    lottiToolStripMenuItem.Visible = false;
                    gestioneFormuleOrfaneToolStripMenuItem.Visible = false;
                    elencoFattureToolStripMenuItem.Visible = false;

                    elencoPOSToolStripMenuItem.Visible = true;
                }
            }
        }

        void lf_ApplicationShutdown(object sender, EventArgs e)
        {
            this.Close();
        }

        #region Form Handlers...
        private bool CheckOpenForm(string formName)
        {
            bool retValue = false;

            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == formName)
                {
                    retValue = true;
                    m_currentForm = f;
                    f.Focus();
                    break;
                }
            }

            return retValue;
        }

        private Form ShowForm<T>() where T : Form, new()
        {
            T ar = default(T);

            try
            {
                System.Threading.Thread.CurrentPrincipal = m_operatore;

                if (!System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
                {
                    MessageBox.Show("E' necessario effettuare il Login !");
                    return null;
                }

                if (!CheckOpenForm(typeof(T).Name))
                {
                    ar = new T();

                    ar.MdiParent = this;
                    ar.WindowState = FormWindowState.Maximized;
                    ar.TopLevel = false;
                    m_currentForm = ar;

                    ((IForm)ar).InitializeForm();

                    ar.Show();
                }

                return ar;
            }
            catch (System.Security.SecurityException sex)
            {
                MessageBox.Show("Accesso non autorizzato !");
                return null;
            }
            catch (ObjectDisposedException odEx)
            {
                string nn = odEx.ObjectName;

                return null;
            }
            catch (Exception ex)
            {
                string msg1 = ex.Message;
                string msg2 = string.Empty;

                if (ex.InnerException != null)
                {
                    if (ex.InnerException.GetType() == typeof(System.Security.SecurityException))
                    {
                        msg2 = string.Format("Accesso non autorizzato !\n{0}", ex.InnerException.Message);
                    }
                }

                MessageBox.Show(string.Format("{0}\n{1}", msg1, msg2));
                return null;
            }
        }

        private Form ShowForm<T>(bool checkAuthentication) where T : Form, new()
        {
            T ar = default(T);

            try
            {
                if (checkAuthentication)
                {
                    if (!System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
                    {
                        MessageBox.Show("E' necessario effettuare il Login !");
                        return null;
                    }
                }

                if (!CheckOpenForm(typeof(T).Name))
                {
                    ar = new T();

                    ar.MdiParent = this;
                    ar.WindowState = FormWindowState.Maximized;

                    ((IForm)ar).InitializeForm();

                    ar.Show();
                }

                return ar;
            }
            catch (System.Security.SecurityException sex)
            {
                MessageBox.Show("Accesso non autorizzato !");
                return null;
            }
            catch (Exception ex)
            {
                string msg1 = ex.Message;
                string msg2 = string.Empty;

                if (ex.InnerException != null)
                {
                    if (ex.InnerException.GetType() == typeof(System.Security.SecurityException))
                    {
                        msg2 = string.Format("Accesso non autorizzato !\n{0}", ex.InnerException.Message);
                    }
                }

                MessageBox.Show(string.Format("{0}\n{1}", msg1, msg2));
                return null;
            }
        }
        #endregion

        #region Menu Handlers...
        private void tinteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ShowAnagrafica<TintaManager>();
        }

        private void polveriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ShowAnagrafica<AnagraficaPolveri>();
        }

        private void operatoriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaOperatori>(false);
        }

        private void test2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ShowAnagrafica<Test2>();
        }

        private void impiantiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaImpianti>();
        }

        private void scatoleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaScatole>();
        }

        private void fornitoriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaFornitori>();
        }

        private void famiglieColoriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaFamigliaColori>();
        }

        private void coloriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaColori>();
        }

        private void polveriToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaPolveri2>();
        }

        private void caricoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<CaricoMovimenti>();
        }

        private void scaricoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<ScaricoMovimenti>();
        }

        private void amministrazioneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<CronologiaMovimenti>();
        }

        private void amministrazione2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<Amministrazione2>();
        }

        private void tracciablitàToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<ReportTracciabilita>();
        }

        private void configurazioneMaschereToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<FrameworkLib.Configurations.FormsConfiguration.AnagraficaConfigurazioneMaschere>();
        }

        private void reportDirezionaleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void affiancaOrizzontaleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void affiancaVerticaleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileVertical);
        }

        private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade);
        }

        private void disponiIconeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void refresfCacheToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrameworkLib.Utilities.Singleton<GestionePolveriLib.Cache.LookUpData>.Instance.DataLoaded += new EventHandler(Instance_DataLoaded);
            FrameworkLib.Utilities.Singleton<GestionePolveriLib.Cache.LookUpData>.Instance.Refresh();
        }

        private void ruoliToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaRuoli>();
        }

        //private void reportDirezionaleToolStripMenuItem1_Click(object sender, EventArgs e)
        //{
        //    ShowForm<Reports.ReportDirezionale>();
        //}

        //private void dettaglioPolveriXXXXToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    ShowForm<ReportDirezionaleDettaglioPolveriXXXX>();
        //}

        private void ruoliToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaRuoli>();
        }

        private void configurazioneMascheraToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<FrameworkLib.Configurations.FormsConfiguration.ColumnsConfigurationManager>();
        }
        #endregion

        void Instance_DataLoaded(object sender, EventArgs e)
        {
            FrameworkLib.Utilities.Singleton<GestionePolveriLib.Cache.LookUpData>.Instance.DataLoaded -= new EventHandler(Instance_DataLoaded);
            
            MessageBox.Show("Cache ricaricata !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }

        private void composizioneColoriToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            ShowForm<VerniciatoreScortaMinima>();
        }

        private void reportDirezionaleToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            ShowForm<ReportDirezionaleForm>();
        }

        private void abiltaTastierinoNumericoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.abiltaTastierinoNumericoToolStripMenuItem.Checked = !this.abiltaTastierinoNumericoToolStripMenuItem.Checked;

            //FrameworkLib.Utilities.Singleton<FrameworkLib.GlobalConfiguration>.Instance.Update("AbilitaTastierino", this.abiltaTastierinoNumericoToolStripMenuItem.Checked);
        }

        private void quickReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<GestionePolveri2.QuickReportInfo.QuickReportInfoDialog>();
        }

        private void coloriInProduzioneSLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ShowForm<ComposizioneColoreManagerExt4>();
        }

        private void visualizzaRagguppamentoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ComposizioneColoreManagerExt4 f = (ComposizioneColoreManagerExt4)ShowForm<ComposizioneColoreManagerExt4>();
            if (f == null)
            {
                ((ComposizioneColoreManagerExt4)m_currentForm).ShowGroups = true;
            }
            else
            {
                f.ShowGroups = true;
            }
        }

        private void visualizzazioneNormaleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ComposizioneColoreManagerExt4 f = (ComposizioneColoreManagerExt4)ShowForm<ComposizioneColoreManagerExt4>();
            if (f == null)
            {
                ((ComposizioneColoreManagerExt4)m_currentForm).ShowGroups = false;
            }
            else
            {
                f.ShowGroups = false;
            }
        }

        private void cambiaLoginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DoLogin();
        }

        private void lottiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaLottiOrfani>();
        }

        private void gestioneFormuleOrfaneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaFormuleOrfane>();
        }

        private void turniToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaTurni>();
        }

        private void elencoPartiteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ShowForm<ElencoPartite>();

            if (m_currentForm is ScaricoMovimenti)
            {
                Turno m_turno = ((ScaricoMovimenti)m_currentForm).Turno;
                Impianto m_impianto = ((ScaricoMovimenti)m_currentForm).Impianto;
                DateTime m_dataMovimento = ((ScaricoMovimenti)m_currentForm).DataMovimento;

                if ((m_turno != null) && (m_impianto != null))
                {
                    ElencoPartite ep = new ElencoPartite();
                    ep.InitializeForm(m_turno.Descrizione, m_impianto.Nome, m_dataMovimento);
                    ep.ShowOnMonitor(1);
                }
                else
                {
                    MessageBox.Show("Selezionare Turno ed Impianto !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            //ElencoPartite ep = new ElencoPartite();
            //ep.InitializeForm();
            //ep.ShowOnMonitor(1);
        }

        private void elencoPOSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ShowForm<AnagraficaPOS>();
            ShowForm<AnagraficaPOS2>();
        }

        private void elencoPrenotazioniToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<ElencoPrenotazioni>();
        }

        private void elencoFattureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaFatture>();
        }

        private void controlloAccessoVerniciatoriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<ControlloAccessoVerniciatori>();
        }

        private void gestioneTipologiaScortaMinimaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowForm<AnagraficaTipologiaScortaMinima>();
        }
    }

    public class KeystrokMessageFilter : System.Windows.Forms.IMessageFilter
    {
        public event EventHandler KeyCombinationPressed;

        public KeystrokMessageFilter() { }

        #region Implementation of IMessageFilter

        public bool PreFilterMessage(ref Message m)
        {
            if ((m.Msg == 256 /*0x0100*/))
            {
                switch (((int)m.WParam) | ((int)Control.ModifierKeys))
                {
                    case (int)(Keys.F12):
                        {
                            if (KeyCombinationPressed != null)
                            {
                                KeyCombinationPressed(this, EventArgs.Empty);
                            }
                        }
                        break;

                    case (int)(Keys.Control | Keys.Alt | Keys.K):
                        {
                            //MessageBox.Show("You pressed ctrl + alt + k");

                            if (KeyCombinationPressed != null)
                            {
                                KeyCombinationPressed(this, EventArgs.Empty);
                            }
                        }
                        break;
                    //This does not work. It seems you can only check single character along with CTRL and ALT.
                    //case (int)(Keys.Control | Keys.Alt | Keys.K | Keys.P):
                    //    MessageBox.Show("You pressed ctrl + alt + k + p");
                    //    break;
                    //case (int)(Keys.Control | Keys.C): MessageBox.Show("You pressed ctrl+c");
                    //    break;
                    //case (int)(Keys.Control | Keys.V): MessageBox.Show("You pressed ctrl+v");
                    //    break;
                    //case (int)Keys.Up: MessageBox.Show("You pressed up");
                    //    break;
                }
            }
            return false;
        }

        #endregion


    }
}
